const app = getApp();
import {
  postRequest,
  getRequest,
  postParamsRequest
} from '../../api/request'
import {
  getUrlParam,
  sortToBig,
  noticeNav,
  editTabBar,
} from '../../utils/util'
import moment from '../../utils/moment';
export default function menu() {
  return {
    data: {
      themeColor: app.globalData.themeColor,
      subColor: app.globalData.subColor,
      btnColor: app.globalData.btnColor,
      baseImg: app.globalData.myTestImg,
      myCouponBg1: app.globalData.myCouponBg1,
      StatusBar: app.globalData.StatusBar,
      CustomBar: app.globalData.CustomBar,
      Custom: app.globalData.Custom,
      showStyle: 0, //是否无数据
      isShowNavigationBack: false,
      TabCur: 0,
      tabId: '',
      MainCur: 0,
      VerticalNavTop: 0,
      hotGoodsBoxHeight: 0,
      couponImgBoxHeight: 0,
      saleType: 1, //1外卖，2堂食，3服务员点餐,4门店自取
      orderType: 1, //订单类型：1-外卖，2-堂食，3-服务员点餐,4-自取，5先吃后付 
      deskCode: "", //堂食的卓码
      deskId: "", //堂食的卓码id
      deskName: "",
      goodsInfo: [], //商品信息
      vipInfo: {
        discount: 1,
        levelId: 0
      }, //会员信息
      load: true,
      addGoodsNum: 0,
      shopInfo: {}, //店铺信息
      isShopBannersFinish: false, //banner图是否下载完成
      cateType: 1, //左侧分类风格
      distance_new: "", //离你多远
      couponCount: 0, //优惠券数量
      //推荐商品-----------------------------------开始
      recommendGoodsList: [],
      //推荐商品-----------------------------------结束
      //等待加载
      loadModal: false,
      //购物车-------------------------------------开始
      addShoppingGoodsNum: 0,
      showShoppingCar: false,
      shoppingCarGoodsList: [],
      shoppingCarGoodsListTotal: 0,
      isAllShoppingCarGoods: true,
      showAddShoppingCar: false,
      priceTotal: 0,
      //购物车-------------------------------------结束
      //选规格-------------------------------------开始
      goodsSpec: {},
      //选规格-------------------------------------结束
      showNotice: false, //弹窗广告是否打开
      eventType: '', //弹窗事件类型
      eventParam: '', //弹窗事件参数
      isShowBigImg: false, //大图片弹窗
      bigImg: '', //大图片
      searchIconLeft: 0,
      isPlaceOrder: 0, //是否可以预约下单
      bannerData: '', //广告轮播图

      isFirstBtn:true,  //点击了确认人数


      _num: 0,

      c_num_list: [{
        num: 1,
        action: 'add'
      }, {
        num: 2,
        action: 'add'
      }, {
        num: 3,
        action: 'add'
      }, {
        num: 4,
        action: 'add'
      }, {
        num: 5,
        action: 'add'
      }, {
        num: 6,
        action: 'add'
      }, {
        num: 7,
        action: 'add'
      }, {
        num: 8,
        action: 'add'
      }, {
        num: 9,
        action: 'add'
      }, {
        num: '×',
        action: 'del'
      }, {
        num: 0,
        action: 'add'
      }, {
        num: '确定',
        action: 'confrim'
      }],
      isfrist: app.globalData.isfrist,
      orderId: "",
      showChooseScan: false,
      paymentPriority: 0,

      openCoverCharge: 0, //是否开启就餐人数
      peopleNumber: "", //就餐人数

      isfristShow:false, //第一次进来就展示是否有订单




    },
    /**
     * 用户点击右上角分享
     */
    onShareAppMessage(options) {
      if (options.from == 'button') {
        return {
          title: options.target.dataset.name,
          imageUrl: options.target.dataset.img,
          success: (res) => {
            console.log("转发成功", res);
          },
          fail: (res) => {
            console.log("转发失败", res);
          }
        }
      }
    },
    onLoad(options) {
      if (options?.deskId) {
        wx.setStorageSync('deskId', options.deskId)
        wx.setStorageSync('deskName', options.deskCode)
      }
      
      console.log('onloadoption', options)
      console.log('onloadorderType', this.data.orderType)
      console.log('onloadorderID', wx.getStorageSync('orderId'))
      console.log('onloadoPAYMENT', wx.getStorageSync('paymentPriority'))
      console.log('onloadordeskName', wx.getStorageSync('deskName'))
      console.log('onloadordeskName', wx.getStorageSync('deskId'))
      //获取店铺信息
      this.getShopInfo();
      let that = this;
      //获取小程序状态条
      wx.getSystemInfo({
        success: e => {
          let capsule = wx.getMenuButtonBoundingClientRect();
          that.setData({
            searchIconLeft: capsule.left - 60,
          });
        }
      })
      this.setData({
        loadModal: true,
      });
      console.log("进来的参数", options);
      //桌码
      if (options.deskCode) {
        let deskCode = decodeURIComponent(options.deskCode);
        let deskId = decodeURIComponent(options.deskId);
        this.setData({
          deskCode: deskCode,
          deskId: deskId,
        })

      }
      //分类定位位置
      if (options.tabId) {
        this.setData({
          tabId: options.tabId,
        })
      }
      this.setData({
        isShowNavigationBack: this.getPageType(),
        
      })
      app.globalData.isfristShow = true
      this.getFirstOnlineNotice();



    },
 
    /**
     * 生命周期函数--监听页面显示
     */
    onShow: function () { 
      console.log('  app.globalData.already',  app.globalData.already)
      console.log( app.globalData.isTrue)
      app.globalData.isTrue = true;
      console.log( app.globalData.isTrue)
      if(app.globalData.already){
        app.globalData.already = false;
        this.onLoad()
     
      }
      if (!wx.getStorageSync('deskId') && wx.getStorageSync('paymentPriority') == 1 && (this.data.orderType == 2 || this.data.orderType == 3)) {
        console.log('onshowssjinlaile ', wx.getStorageSync('deskId'))
        this.setData({
          showChooseScan: true
        })
      }
      if (wx.getStorageSync('deskId') && wx.getStorageSync('paymentPriority') == 0) {
        this.getShopInfo()
      }
      editTabBar(this);
      // this.getShopInfo();
      // if (wx.getStorageSync('deskId') && wx.getStorageSync('orderId')) {
      //   this.getQueryDesk()
      // }
      this.getQueryDesk()
      let that = this;

      //如果没有token,则需要重新登录获取个人信息等，避免缺少id导致数据无法获取
      if (app.token == "" || app.token == undefined) {
        app.initLogin().then(res => {
          that.initData()
        }).catch(err => {})
      } else {
        that.initData();
      }
      that.getBannerList();
      try {
        let isfrist_value = wx.getStorageSync('isfrist')
        let isfrist_timestamp = wx.getStorageSync('isfrist_timestamp')
        let people_number = wx.getStorageSync('peopleNumber')
        let timestamp = new Date().getTime()
        if (isfrist_value && isfrist_timestamp) {
          let hour = (timestamp - isfrist_timestamp) / 1000 / 3600
          console.log(hour, 'hour')
          if (hour <= 2) {
            console.log('2小时内已经支付过茶位费')
            app.globalData.isfrist = 1
            app.globalData.people_num = people_number
            this.setData({
              isfrist: 1
            })
          } else {
            this.setData({
              isfrist: 0
            })
          }
        }
      } catch (e) {

      }
    },
    //初始化数据
    initData() {

      //获取商品信息
      this.getFoodList();
    },

    onReady() {},
    //返回上一级
    onNavigationBack() {
      wx.switchTab({
        url: '../../pages/index/index',
      })
    },
    getPeopleNumClose() {
      this.setData({

      })
    },
    getPeopleNum(e) {
      let action = e.currentTarget.dataset.action
      let num = e.currentTarget.dataset.num
      let peopleNumber = this.data.peopleNumber
      if (action == 'add') {
        peopleNumber += num
      }
      if (action == 'del') {
        peopleNumber = ''
      }

      this.setData({
        peopleNumber: peopleNumber
      })
      if (action == 'confrim' && peopleNumber > 0) {

        app.globalData.isfrist = 1;
        app.globalData.isFirstBtn = false;
        this.setData({
          isfrist: 1,
          isFirstBtn:false
        })
        wx.setStorageSync('isfrist', 1)
        wx.setStorageSync('isfrist_timestamp', new Date().getTime())

        try {
          wx.setStorageSync('peopleNumber', this.data.peopleNumber)
          console.log('缓存的就餐人数：', this.data.peopleNumber)
          try {
            var value = wx.getStorageSync('peopleNumber')
            if (value) {
              console.log('缓存的就餐人数--', value)
            }
          } catch (e) {
            // Do something when catch error
          }
        } catch (e) {}

        app.globalData.people_num = this.data.peopleNumber
      }
    },
    //获取个人信息
    getUserBaseInfo() {
      let that = this;
      wx.showLoading({
        title: "加载中...",
        icon: "none"
      });
      return new Promise(function (resolve, reject) {
        getRequest("/api/vip/getUserBaseInfo", {
          memberId: app.myInfo.memberId
        }).then((res) => {

          if (res.data.data != null) {
            wx.setStorageSync('userInfo', res.data.data);
            that.setData({
              userInfo: res.data.data,
            })
          }
          wx.hideLoading();
          resolve(res);
        }).catch((err) => {
          wx.hideLoading();
          reject(err);
        });
      });
    },
    getQueryDesk() {

      if (true) {
        let parame = {
          deskId: app.globalData.deskId || wx.getStorageSync('deskId')
        }
        getRequest("/api/desk/queryDesk", parame).then((res) => {

          let obj = res.data.data;
          if (obj.orderId ) {
            app.globalData.deskName = obj.tableName;
            app.globalData.deskId = obj.id;

            wx.setStorageSync('deskId', obj.id)
            wx.setStorageSync('deskName', obj.tableName)
            wx.setStorageSync('orderId', obj.orderId)
            this.setData({
              orderId: obj.orderId,
              deskName: obj.tableName,

              // showChooseScan:true
            })
            if (obj?.numberPeople != 0 ) {
              wx.setStorageSync('peopleNumber', obj?.numberPeople)
              this.setData({
                peopleNumber: obj?.numberPeople,
    
              })
            }
            // wx.getStorageSync('addBtnFoods') &&
            if ( wx.getStorageSync('openCoverCharge') != 1 && wx.getStorageSync('paymentPriority') == 1) {
              console.log("ddddddd")
              wx.showModal({
                title: '提示',
                content: '该桌子已存在订单，是否加菜？',
                cancelText: "查看订单",
                success(res) {
                  // wx.setStorageSync('addBtnFoods', false)
                  if (res.confirm) {

                  } else {
                    wx.navigateTo({
                      url: '../orderDetail/orderDetail?orderId=' + obj.orderId
                    })
                  }
                }
              })
            }
     
            if (wx.getStorageSync('openCoverCharge') == 1 && wx.getStorageSync('peopleNumber') && wx.getStorageSync('orderId') &&  app.globalData.isfristShow && wx.getStorageSync('paymentPriority') == 1 && this.data.orderType == 2) {
              console.log("ccccc")
              wx.showModal({
                title: '提示',
                content: '该桌子已存在订单，是否加菜？',
                cancelText: "查看订单",
                success(res) {
                  app.globalData.isfristShow = false;
                  if (res.confirm) {
                   
                  } else {
                    wx.navigateTo({
                      url: '../orderDetail/orderDetail?orderId=' + obj.orderId
                    })
                  }
                }
              })
            }
          } else {
            console.log(' app.globalData.people_num', app.globalData.people_num)
            app.globalData.deskName = obj.tableName;
            app.globalData.deskId = obj.id;
            wx.setStorageSync('deskId', obj.id)
            wx.setStorageSync('deskName', obj.tableName)
            wx.setStorageSync('orderId', "")
            this.setData({
              orderId: "",
              deskName: obj.tableName,
              // showChooseScan:true
            })
            // wx.setStorageSync('peopleNumber', "")
            this.setData({
              peopleNumber: app.globalData.people_num || "",
              isfrist: app.globalData.people_num >0? 1:0,
            })
      
          }
          if( wx.getStorageSync('orderId') && wx.getStorageSync('paymentPriority') == 0 ){
            wx.setStorageSync('orderId', "")
            wx.setStorageSync('peopleNumber', "")
            this.setData({
              orderId:"",
              peopleNumber:"",
            })
          }
          if(wx.getStorageSync('orderId') && wx.getStorageSync('openCoverCharge') == 1 ){
            this.setData({
            isfrist:0
          })
          }
          if(wx.getStorageSync('deskId') && wx.getStorageSync('openCoverCharge') == 1 && !obj.numberPeople ){
            this.setData({
            isfrist:0
          })
          }

          if((app.globalData.addBtn ||  obj.numberPeople >0 ) && wx.getStorageSync('openCoverCharge') == 1 ){
            this.setData({
              isfrist:1
            })
          }
       


        }).catch((err) => {

        });
      }
    },
    //扫描餐桌二维码
    scanQrcodeEnter() {
      let self = this;
      let deskCode = '';
      let deskId = '';
      wx.scanCode({
        success: (res) => {

          try {

            deskCode = getUrlParam('deskCode', res.path);
            deskId = getUrlParam('deskId', res.path);
            app.globalData.deskCode = deskCode;
            app.globalData.deskId = deskId;
            app.globalData.deskName = deskCode;
            wx.setStorageSync('deskName', deskCode)
            wx.setStorageSync('deskCode', deskCode)
            wx.setStorageSync('deskId', deskId)
            self.setData({
              showChooseScan: false,
              deskCode: deskCode,
              deskId: deskId,
              deskName: deskCode,

            });
            this.getQueryDesk()

          } catch (e) {
            wx.showToast({
              title: '二维码不正确',
              icon: 'none'
            })

          };
        }
      })
    },
    //前往搜索页
    toSearchPage() {
      let that = this;
      let goodsList = [];
      that.data.goodsInfo.forEach((item, index) => {
        goodsList = goodsList.concat(item.goodsList);
      });
      app.globalData.goodsList = goodsList;
      wx.navigateTo({
        url: '../../pages/goodsListSearch/goodsListSearch?saleType=' + that.data.saleType + '&orderType=' + that.data.orderType + '&discount=' + that.data.vipInfo.discount,
      })
    },
    //判断是否为tab页
    getPageType() {
      const currentPages = getCurrentPages()
      const current = currentPages[currentPages.length - 1]
      let have = false
      app.customTabBar.list.forEach((item, index) => {
        if (item.pagePath == current.route) {
          have = true
        }
      })
      return !have;
    },
    //返回周几信息
    getweek(e) {
      var week = ['1', '2', '3', '4', '5', '6', '7']
      return week[e - 1]
    },
    //获取轮播图
    getBannerList() {
      let that = this;

      postParamsRequest("/api/banner/list", {
        beid: app.beid,
        bannerType: 'order',
      }, 2).then((res) => {

        if (res.data.data != null) {
          let bannerData = '';
          for (let i = 0; i < res.data.data.length; i++) {
            if (res.data.data[i].bannerType == 'order' && res.data.data[i].isShow == 1 && res.data.data[i].bannerUrl != '') {
              bannerData = res.data.data[i];
              bannerData.bannerUrl = bannerData.bannerUrl.split(',');
              that.setData({
                bannerData: bannerData,
              })
              return;
            }
          }
          that.setData({
            bannerData: bannerData,
          })
        }

      }).catch((err) => {

      });

    },
    //获取店铺信息
    getShopInfo() {

      let that = this;
      getRequest("/api/shop/getShopInfo", {
        beid: app.beid
      }).then(res => {
        wx.setStorageSync('openCoverCharge', res.data.data.openCoverCharge)
        wx.setStorageSync('paymentPriority', res.data.data.paymentPriority)
        this.setData({
          paymentPriority: res.data.data.paymentPriority,
          openCoverCharge: res.data.data.openCoverCharge
        })
     
        
        if (res.data.data.openCoverCharge == 1 && !wx.getStorageSync('deskId') && (this.data.orderType == 2)) {
          this.setData({
            showChooseScan: true
          })

        }

        // 当是在点餐主页   并且获取内存餐桌号不能为空  当前店铺开通先吃后付 并且（当前订单类型为先吃后付5获2）
        if (app.globalData.mainIndex && !wx.getStorageSync('deskId') && res.data.data.paymentPriority == 1 && this.data.orderType == 2) {
          this.setData({
            showChooseScan: true
          })
        }

        console.log('getShopInfo里面的this.data.orderType', this.data.orderType)
        console.log('getShopInfo里面的 app.globalData.orderType', app.globalData.orderType)

        let orderTypeOrder = that.data.orderType;
        console.log('判断店铺销售方式', res.data.data)
        //判断店铺销售方式
        if (res.data.data.salesType.indexOf(orderTypeOrder) == -1) {
          let showTitle = "";
          if (that.data.orderType == 1) {
            showTitle = "外卖";
          } else if (that.data.orderType == 2) {
            showTitle = "堂食";
          } else if (that.data.orderType == 4) {
            showTitle = "自取";
          }
          wx.showModal({
            title: '提示',
            content: '店铺暂不支持' + showTitle,
            showCancel: false,
            success(res) {
              if (res.confirm) {} else if (res.cancel) {}
            }
          })
        }

        //如果是关店则不给预约
        if (res.data.data.shopOpen == 1 || res.data.data.openDay == '') {
          this.setData({
            isPlaceOrder: 0,
          })
        } else {
          this.setData({
            isPlaceOrder: res.data.data.isPlaceOrder,
          })
        }

        //判断营业时间
        res.data.data.shopOpenTime = false;
        if (res.data.data.openDay != '' && res.data.data.openTimePeriods.length != 0) {
          let openTime = JSON.parse(JSON.stringify(res.data.data.openTimePeriods))
          let openTime2 = []
          let weekDay = this.getweek(moment().format('E'))
          //判断是否跨天
          for (let i = 0; i < openTime.length; i++) {
            if (moment(moment().format('YYYY-MM-DD') + ' ' + openTime[i].end).diff(moment(moment().format('YYYY-MM-DD') + ' ' + openTime[i].begin), 'minutes') < 0) {
              openTime2.push({
                end: '24:00',
                begin: openTime[i].begin
              });
              openTime2.push({
                end: openTime[i].end,
                begin: '00:00'
              });
            } else {
              openTime2.push(openTime[i])
            }
          }
          openTime = openTime2;

          if (res.data.data.openDay.indexOf(weekDay) != -1) {
            for (let i = 0; i < openTime.length; i++) {
              if (moment(moment().format('YYYY-MM-DD HH:mm')).diff(moment(moment().format('YYYY-MM-DD') + ' ' + openTime[i].begin), 'minutes') >= 0 && moment(moment().format('YYYY-MM-DD HH:mm')).diff(moment(moment().format('YYYY-MM-DD') + ' ' + openTime[i].end), 'minutes') <= 0) {
                res.data.data.shopOpenTime = true;
              }
            }
          }
        }
        if (!res.data.data.shopOpenTime) {
          res.data.data.shopOpen = 1
        }

        this.setData({
          shopInfo: res.data.data,
          cateType: res.data.data.cateType,
        })
        app.shopInfo = res.data.data;
        //主题色
        if (res.data.data.colorType != '' && res.data.data.colorType != null) {
          app.globalData.themeColor = res.data.data.colorType.themeColor;
          app.globalData.subColor = res.data.data.colorType.subColor;
          app.globalData.btnColor = res.data.data.colorType.btnColor;
          that.setData({
            themeColor: res.data.data.colorType.themeColor,
            subColor: res.data.data.colorType.subColor,
            btnColor: res.data.data.colorType.btnColor,
          })
        }
        wx.setStorageSync('shopInfo', res.data.data);

        // todo 
      }).catch((err) => {

      });
    },
    //开大图弹窗
    showBigImg(e) {

      this.setData({
        isShowBigImg: true,
        bigImg: e.currentTarget.dataset.img,
      });
    },
    //关大图弹窗
    hideBigImg() {
      this.setData({
        isShowBigImg: false,
      });
    },
    //banner图是否下载完成
    shopBannersFinish(e) {

      this.setData({
        isShopBannersFinish: true,
      });
    },
    //广告弹窗----------------------------------------------------------开始
    //获取弹窗
    getFirstOnlineNotice() {
      let self = this;
      getRequest('/api/notice/getFirstOnlineNotice', {
        effectPage: 2
      }).then((res) => {

        if (res.statusCode == 200) {
          if (res.data.data != null) {
            let data = res.data.data;
            if (data.isTurn == 1 && data.turnEvent != '') {
              self.data.eventType = JSON.parse(data.turnEvent).eventType
              self.data.eventParam = JSON.parse(data.turnEvent).eventParam
            }
            if (!data.id) {
              return
            }
            //判断时间，永久还是限时
            let isInvalid = data.isForever == 0 && (Date.parse(new Date()) < Date.parse(data.startTime) || Date.parse(new Date()) > Date.parse(data.endTime));
            if (isInvalid) {
              return;
            }
            //打开即显示1，只显示一次2，每天第一次打开显示3
            //是否显示过
            let noticeInfo = wx.getStorageSync('noticeKey');
            if (data.showType == 1 && ((!noticeInfo || noticeInfo.id != data.id))) {
              self.setShow(self, data.imageUrl);
              // setStorage(data);
              return;
            }
            if (data.showType == 1 && ((!noticeInfo || noticeInfo.id == data.id))) {
              self.setShow(self, data.imageUrl);
              setStorage(data);
              return;
            }
            try {
              if (!noticeInfo || noticeInfo.id != data.id) {
                self.setShow(self, data.imageUrl);
                self.setStorage(data);
              } else {
                if (data.showType == 2 && noticeInfo.openTime) {
                  return;
                } else if (getYMD(new Date(noticeInfo.openTime)) != getYMD(new Date()) && data.showType == 3) {
                  self.setShow(self, data.imageUrl);
                  self.setStorage(data);
                }
              }
            } catch (e) {}
          }
        }
      })
    },
    //显示弹窗
    setShow(self, url) {
      self.setData({
        showNotice: true,
        noticeImgUrl: url
      })
    },
    //设置弹窗缓存，用以判断是否打开过等
    setStorage(data) {
      wx.setStorageSync("noticeKey", {
        'id': data.id,
        'isForever': data.isForever,
        'startTime': data.startTime,
        'endTime': data.endTime,
        "showType": data.showType,
        'noticeImgUrl': data.imageUrl,
        'openTime': Date.parse(new Date()),
      })
    },
    //弹窗跳转
    navLink() {
      this.hideNotice();
      if (this.data.eventType != '') {
        noticeNav(this.data.eventType, this.data.eventParam)
      }
    },
    //关闭弹窗
    hideNotice() {
      this.setData({
        showNotice: false,
      });
    },
    //广告弹窗----------------------------------------------------------结束
    //获取商品
    getFoodList() {
      let self = this;
      console.log("that.data.orderType",this.data.orderType);
      //是否打开购物车，再来一单
      if (app.globalData.isOpenCart) {
        wx.showToast({
          title: '已加入购物车',
          icon: 'none'
        })
        this.setData({
          showShoppingCar: true,
        })
        app.globalData.isOpenCart = false;
      }

      //购物车商品
      let cartList = app.globalData.cartList;
      //购物车数
      let shoppingCarGoodsListTotal = 0;
      cartList.forEach((item, index) => {
        shoppingCarGoodsListTotal += item.count;
      });
      this.setData({
        shoppingCarGoodsList: cartList,
        shoppingCarGoodsListTotal: shoppingCarGoodsListTotal,
      })
    
      // return
      let param = {
        saleType: this.data.orderType,
      };
      // if (this.data.orderType == 5) {


      // } else {

      //   app.globalData.orderType = this.data.orderType
      //   param = {
      //     saleType: this.data.orderType,
      //   };
      // }


      //提前把购物车数量赋值
      let list2 = this.data.goodsInfo
      for (let i = 0; i < list2.length; i++) {
        //规格数量
        list2[i].goodsList.forEach((item, index) => {
          item.count = 0;
          //单规格商品
          if (item.isGroup == 0 && item.isSku == 0) {
            cartList.forEach((item2, index2) => {
              if (item2.goodsId == item.id) {
                item.count = item2.count;
              }
            });
          }
        });
      }
      this.setData({
        goodsInfo: list2,
      })
      this.countPriceTotal();
      getRequest("/api/goods/getFoodList", param).then((res) => {


        let list = res.data.data.goodsInfo;
        let list2 = res.data.data.recommendGoodsList;

        //会员等级，会员折扣计算
        let vipInfo1 = {
          discount: 1,
          levelId: res.data.data.vipInfo.levelId
        }
        if (res.data.data.vipInfo.discount * 1 < 10 && res.data.data.vipInfo.discount * 1 > 0) {
          vipInfo1.discount = (res.data.data.vipInfo.discount * 0.1).toFixed(2) * 1
        }
        //商品列表
        for (let i = 0; i < list.length; i++) {
          //获取弹窗带的位置参数
          if (this.data.tabId != '') {
            if (list[i].id == this.data.tabId) {
              let self = this;
              setTimeout(function () {
                self.setData({
                  TabCur: i,
                  MainCur: i,
                  VerticalNavTop: (i - 1) * 50
                })
              }, 100)

            }
          }
          list[i].cateId = list[i].id;
          list[i].id = i;

          //规格数量
          list[i].goodsList.forEach((item, index) => {
            item.count = 0;
            item.skuId = 0;
            item.skuStock = 0;
            item.cateId = list[i].cateId;
            //是否显示会员价
            let vipLevels = item.vipLevel == '' ? [] : item.vipLevel.split(",");
            if (vipLevels.includes(vipInfo1.levelId.toString())) {
              item.isShowVipPrice = true;
            } else {
              item.isShowVipPrice = false;
            }

            //单规格商品
            if (item.isGroup == 0 && item.isSku == 0) {
              cartList.forEach((item2, index2) => {
                if (item2.goodsId == item.id) {
                  item.count = item2.count;
                }
              });
            }
          });
        }
        //是否无数据
        if (list.length == 0) {
          this.setData({
            showStyle: 2,
          });
        } else {
          this.setData({
            showStyle: 0,
          });
        }

        //推荐商品
        for (let i = 0; i < list2.length; i++) {
          //是否显示会员价
          let vipLevels = list2[i].vipLevel == '' ? [] : list2[i].vipLevel.split(",");
          if (vipLevels.includes(vipInfo1.levelId.toString())) {
            list2[i].isShowVipPrice = true;
          } else {
            list2[i].isShowVipPrice = false;
          }
        }
        this.setData({
          goodsInfo: list,
          vipInfo: vipInfo1,
          listCur: list[0] == undefined ? 0 : list[0].id,
          shopInfo: app.shopInfo,
          recommendGoodsList: list2,
          couponCount: res.data.data.shopInfo.couponCount,
        })

        //获取人气推荐和领取盒子高度，用于滚动计算
        if (this.data.recommendGoodsList.length > 0) {
          let hotGoodsBoxView = wx.createSelectorQuery().select("#hot-goods-box");
          hotGoodsBoxView.fields({
            size: true
          }, data => {
            self.setData({
              hotGoodsBoxHeight: data.height,
            });
          }).exec();
        }
        if (this.data.couponCount > 0) {
          let couponImgBoxView = wx.createSelectorQuery().select("#coupon-img-box");
          couponImgBoxView.fields({
            size: true
          }, data => {
            self.setData({
              couponImgBoxHeight: data.height,
            });
          }).exec();
        }
        //初始化是否计算商品高度，这里要赋值为true,因为数据刷新会清掉商品高度，需要重新获取
        this.setData({
          load: true,
        })


        if (app.shopInfo.lnglat != "") {
          this.getLocations();
        }

        this.countPriceTotal();
        self.setData({
          loadModal: false,
        });
      }).catch((err) => {});
    },
    //获取当前位置计算和门店距离
    getLocations() {
      let that = this
      wx.getLocation({
        highAccuracyExpireTime: 3000,
        isHighAccuracy: true,
        type: 'gcj02',
        success: (res) => {

          const latitude = res.latitude
          const longitude = res.longitude
          const distance_new2 = this.getDistance2(longitude, latitude, Number(that.data.shopInfo.lnglat.split(',')[0]), Number(that.data.shopInfo.lnglat.split(',')[1]));
          this.setData({
            now_latitude: latitude, //纬度
            now_longitude: longitude, //经度
            distance_new: distance_new2
          })
        },
        fail: (res) => {},
        complete: (res) => {},
      })
    },
    //打开导航
    opLocations() {
      let arr = this.data.shopInfo.lnglat.split(',')
      const latitude = Number(arr[1])
      const longitude = Number(arr[0])
      wx.openLocation({
        latitude,
        longitude,
        name: this.data.shopInfo.shopName,
        address: this.data.shopInfo.address,
        scale: 18
      })
    },
    //计算距离
    getDistance(lat1, lng1, lat2, lng2) {
      let radLat1 = this.Rad(lat1)
      let radLat2 = this.Rad(lat2)
      var a = this.Rad(lat1) - this.Rad(lat2)
      var b = this.Rad(lng1) - this.Rad(lng2)
      var s = 2 * Math.asin(Math.sqrt(Math.pow(Math.sin(a / 2), 2))) + Math.cos(radLat1) * Math.cos(radLat2) * Math.pow(Math.sin(b / 2), 2)
      s = s * 6378.137
      s = Math.round(s * 10000) / 10000
      s = s.toFixed(1) + 'km'
      return s
    },
    getDistance2(lat1, lng1, lat2, lng2) {
      // 地球平均半径
      const EARTH_RADIUS = 6378137;
      // 把经纬度转为度（°）
      // 纬度
      let degree_lat1 = (lat1 * Math.PI) / 180.0;
      let degree_lat2 = (lat2 * Math.PI) / 180.0;
      let a = degree_lat1 - degree_lat2;
      // 经度
      let degree_lng1 = (lng1 * Math.PI) / 180.0;
      let degree_lng2 = (lng2 * Math.PI) / 180.0;
      let b = degree_lng1 - degree_lng2;
      // 距离 （单位：米）
      let s =
        2 *
        Math.asin(
          Math.sqrt(
            Math.pow(Math.sin(a / 2), 2) +
            Math.cos(degree_lat1) *
            Math.cos(degree_lat2) *
            Math.pow(Math.sin(b / 2), 2)
          )
        );
      s = s * EARTH_RADIUS;
      s = Math.round(s * 10000) / 10000 / 1000;
      s = s.toFixed(1) + 'km'
      return s;
    },
    //阻止冒泡事件
    handmiddle(e) {},
    //联系商家
    callShop() {
      wx.makePhoneCall({
        phoneNumber: this.data.shopInfo.servicePhone,
        success: function () {
          console.log("拨打电话成功！")
        },
        fail: function () {
          console.log("拨打电话失败！")
        }
      })
    },
    //打开购物车
    showShoppingCar(e) {
      this.setData({
        showShoppingCar: !this.data.showShoppingCar
      })
    },
    //关闭购物车
    hideShoppingCar(e) {
      this.setData({
        showShoppingCar: false
      })
    },
    //减少商品数量,type:1，商品列；2：购物车，多规格，单规格，有商品id就行;
    onSubGoods(e) {
      let type = e.currentTarget.dataset.type;
      let typeIndex = 0;
      let goodsIndex = 0;
      let goodsInfo = this.data.goodsInfo;
      if (type == 1) {
        typeIndex = e.currentTarget.dataset.typeIndex;
        goodsIndex = e.currentTarget.dataset.goodsIndex;
      } else if (type == 2) {
        //购物车点击需要遍历
        let goodsId = e.currentTarget.dataset.goodsId;
        goodsInfo.forEach((item, index) => {
          item.goodsList.forEach((item2, index2) => {
            if (item2.id == goodsId) {
              typeIndex = index;
              goodsIndex = index2;
            }
          });
        });
      }
      //锁定商品
      let goodsMessage = this.data.goodsInfo[typeIndex].goodsList[goodsIndex];
      console.log(goodsMessage);
      let goodsType = 1; //1单规格，2多规格，3套餐
      if (goodsMessage.isGroup == 0) {
        //商品
        if (goodsMessage.isSku == 0) {
          //单
          goodsType = 1;
        } else {
          //多
          goodsType = 2;
        }
      } else if (goodsMessage.isGroup == 1) {
        //套餐
        goodsType = 3;
      }

      //加入购物车
      let shoppingCarGoodsList = this.data.shoppingCarGoodsList;
      if (goodsType == 1) {
        //无规格无属性
        if (goodsMessage.goodsAttrType.length == 0) {
          if (goodsMessage.count <= 0) {
            return;
          }
          goodsMessage.count -= 1;
          //是否已经存在
          shoppingCarGoodsList.forEach((item, index) => {
            if (item.id == goodsMessage.id) {
              item.count -= 1;
              if (item.count == 0) {
                shoppingCarGoodsList.splice(index, 1);
              }
            }
          });
        } else {
          //无规格有属性
          //属性id
          let arrId = e.currentTarget.dataset.goodsArr;
          //是否已经存在
          shoppingCarGoodsList.forEach((item, index) => {
            if (item.id == goodsMessage.id && item.goodsArrIds == arrId) {
              item.count -= 1;
              if (item.count == 0) {
                shoppingCarGoodsList.splice(index, 1);
              }
            }
          });
        }
      } else if (goodsType == 2) {
        //规格id
        let skuId = e.currentTarget.dataset.goodsSku;
        //属性id
        let arrId = e.currentTarget.dataset.goodsArr;
        //是否已经存在
        shoppingCarGoodsList.forEach((item, index) => {
          if (item.id == goodsMessage.id && item.skuId == skuId && item.goodsArrIds == arrId) {
            item.count -= 1;
            if (item.count == 0) {
              shoppingCarGoodsList.splice(index, 1);
            }
          }
        });
      } else if (goodsType == 3) {
        //规格id
        let skuId = e.currentTarget.dataset.goodsSku;
        //属性id
        let arrId = e.currentTarget.dataset.goodsArr;
        //套餐选项
        let package1 = e.currentTarget.dataset.goodsPackage;
        shoppingCarGoodsList.forEach((item, index) => {
          if (item.id == goodsMessage.id && item.skuId == skuId && item.goodsArrIds == arrId && item.packageListString == package1) {
            item.count -= 1;
            if (item.count == 0) {
              shoppingCarGoodsList.splice(index, 1);
            }
          }
        });
      }

      //购物车数
      let shoppingCarGoodsListTotal = 0;
      shoppingCarGoodsList.forEach((item, index) => {
        shoppingCarGoodsListTotal += item.count;
      });

      let goodsInfoString = 'goodsInfo[' + typeIndex + '].goodsList[' + goodsIndex + ']';

      this.setData({
        [goodsInfoString]: goodsMessage,
        shoppingCarGoodsList: shoppingCarGoodsList,
        shoppingCarGoodsListTotal: shoppingCarGoodsListTotal,
      });
      //如果购物车为空，关闭购物车弹窗
      if (shoppingCarGoodsList.length <= 0) {
        this.setData({
          showShoppingCar: false,
        });
      }
      this.countPriceTotal();

    },
    floatPrice(num) {
      if (num) {
        num = parseFloat(num);
        return parseFloat(num.toFixed(2))
      } else return 0;
    },
    //增加商品数量,type:1，商品列；2，购物车，多规格，单规格，有商品id就行;
    onAddGoods(e) {
      let type = e.currentTarget.dataset.type;
      let typeIndex = 0;
      let goodsIndex = 0;
      let goodsInfo = this.data.goodsInfo;
      if (type == 1) {
        typeIndex = e.currentTarget.dataset.typeIndex;
        goodsIndex = e.currentTarget.dataset.goodsIndex;
      } else if (type == 2) {
        //购物车点击需要遍历
        let goodsId = e.currentTarget.dataset.goodsId;
        goodsInfo.forEach((item, index) => {
          item.goodsList.forEach((item2, index2) => {
            if (item2.id == goodsId) {
              typeIndex = index;
              goodsIndex = index2;
            }
          });
        });
      }
      //锁定商品
      let goodsMessage = this.data.goodsInfo[typeIndex].goodsList[goodsIndex];

      console.log(goodsMessage)
      let goodsType = 1; //1单规格，2多规格，3套餐
      if (goodsMessage.isGroup == 0) {
        //商品
        if (goodsMessage.goodsAttrType.length == 0 && goodsMessage.goodsSpec.length == 0) {
          //单
          goodsType = 1;
        } else {
          //多
          goodsType = 2;
        }
      } else if (goodsMessage.isGroup == 1) {
        //套餐
        goodsType = 3;
      }

      //加入购物车
      let shoppingCarGoodsList = this.data.shoppingCarGoodsList;
      //是否已经存在
      let isHaveGoods = false;

      //判断增加的数量不能大于库存
      if (goodsType == 1) {
        if (goodsMessage.stock <= goodsMessage.count) {
          wx.showToast({
            title: '无库存',
            icon: 'none'
          })
          return;
        } else {
          goodsMessage.count += 1;
        }
        shoppingCarGoodsList.forEach((item, index) => {
          if (item.id == goodsMessage.id && item.skuId == goodsMessage.skuId) {
            item.count += 1;
            isHaveGoods = true;
          }
        });
      } else if (goodsType == 2) {
        console.log(shoppingCarGoodsList);
        //规格id
        let skuId = e.currentTarget.dataset.goodsSku;
        //属性id
        let arrId = e.currentTarget.dataset.goodsArr;
        shoppingCarGoodsList.forEach((item, index) => {
          if (item.id == goodsMessage.id && item.skuId == skuId && item.goodsArrIds == arrId) {
            item.count += 1;
            isHaveGoods = true;
          }
        });
      } else if (goodsType == 3) {
        if (goodsMessage.stock <= goodsMessage.count) {
          wx.showToast({
            title: '无库存',
            icon: 'none'
          })
          return;
        }
        //规格id
        let skuId = e.currentTarget.dataset.goodsSku;
        //属性id
        let arrId = e.currentTarget.dataset.goodsArr;
        //套餐选项
        let package1 = e.currentTarget.dataset.goodsPackage;
        shoppingCarGoodsList.forEach((item, index) => {
          if (item.id == goodsMessage.id && item.skuId == skuId && item.goodsArrIds == arrId && item.packageListString == package1) {
            item.count += 1;
            isHaveGoods = true;
          }
        });
      }

      //是否显示vip价格
      let discount = 1;
      if (goodsMessage.isShowVipPrice) {
        discount = this.data.vipInfo.discount;
      }

      //不存在时
      if (!isHaveGoods) {
        shoppingCarGoodsList.push({
          checked: true,
          id: goodsMessage.id,
          attrList: [],
          cateId: goodsMessage.cateId,
          count: goodsMessage.count,
          goodsId: goodsMessage.id,
          packageList: [],
          packageListString: JSON.stringify([]),
          skuId: 0,
          thumbUrl: goodsMessage.thumbUrl,
          goodsName: goodsMessage.goodsName,
          goodsSkuName: "",
          goodsArrName: "",
          goodsArrIds: "",
          shopPrice: this.floatPrice(goodsMessage.shopPrice * discount),
          originPrice: goodsMessage.shopPrice,
        });
      }

      //购物车数
      let shoppingCarGoodsListTotal = 0;
      shoppingCarGoodsList.forEach((item, index) => {
        shoppingCarGoodsListTotal += item.count;
      });
      let goodsInfoString = 'goodsInfo[' + typeIndex + '].goodsList[' + goodsIndex + ']';
      this.setData({
        [goodsInfoString]: goodsMessage,
        shoppingCarGoodsList: shoppingCarGoodsList,
        shoppingCarGoodsListTotal: shoppingCarGoodsListTotal,
      });

      this.countPriceTotal();
    },
    //计算合计
    countPriceTotal() {
      let priceTotal = 0;
      this.data.shoppingCarGoodsList.forEach((item, index) => {
        if (item.checked) {
          priceTotal += item.shopPrice * item.count;
        }
      });
      this.setData({
        priceTotal: priceTotal.toFixed(2) * 1,
      });
      app.globalData.cartList = this.data.shoppingCarGoodsList;
    },
    //购物车多选框改变时
    onShoppingCheck(e) {
      console.log(e.detail.value);
      //判断是否全选
      if (e.detail.value.length == this.data.shoppingCarGoodsList.length) {
        this.setData({
          isAllShoppingCarGoods: true
        });
      } else {
        this.setData({
          isAllShoppingCarGoods: false
        });
      }
      this.data.shoppingCarGoodsList.forEach((item, index) => {
        if (e.detail.value.indexOf(item.id + '-' + item.skuId + '-' + item.goodsArrIds + '-' + item.packageListString) != -1) {
          item.checked = true;
        } else {
          item.checked = false;
        }
      });

      this.setData({
        shoppingCarGoodsList: this.data.shoppingCarGoodsList
      })
      this.countPriceTotal();
    },
    //更新全选状态方法
    updateAllShoppingCarGoods() {
      let selectN = 0;
      this.data.shoppingCarGoodsList.forEach((item, index) => {
        if (item.checked) {
          selectN += 1;
        }
      });
      //判断是否全选
      if (selectN == this.data.shoppingCarGoodsList.length) {
        this.setData({
          isAllShoppingCarGoods: true
        });
      } else {
        this.setData({
          isAllShoppingCarGoods: false
        });
      }
    },
    //购物车点击全选时
    onAllShoppingCarGoods() {
      console.log(this.data.isAllShoppingCarGoods);
      this.setData({
        isAllShoppingCarGoods: !this.data.isAllShoppingCarGoods
      });
      if (this.data.isAllShoppingCarGoods) {
        this.data.shoppingCarGoodsList.forEach((item) => {
          item.checked = true;
        });
      } else {
        this.data.shoppingCarGoodsList.forEach((item) => {
          item.checked = false;
        });
      }
      this.setData({
        shoppingCarGoodsList: this.data.shoppingCarGoodsList
      })
      this.countPriceTotal()
    },

    //清空购物车
    clearShoppingCart() {
      let that = this;
      wx.showModal({
        title: '提示',
        content: '确认清空购物车？',
        confirmText: "是",
        success(res) {
          if (res.confirm) {
            that.data.goodsInfo.forEach((item, index) => {
              item.goodsList.forEach((item2, index2) => {
                item2.count = 0;
              });
            });
            that.setData({
              goodsInfo: that.data.goodsInfo,
              shoppingCarGoodsList: [],
              showShoppingCar: false,
              shoppingCarGoodsListTotal: 0,
            })
            that.countPriceTotal();
          } else if (res.cancel) {}
        }
      })
    },

    //打开添加购物车
    showAddShoppingCar(e) {
      let id = e.currentTarget.dataset.id;
      let data = {};
      this.data.goodsInfo.forEach((item, index) => {
        item.goodsList.forEach((item2, index2) => {
          if (id == item2.id) {
            data = JSON.parse(JSON.stringify(item2));
          }
        });
      });

      if (data.stock <= 0) {
        wx.showToast({
          title: '无库存',
          icon: 'none'
        })
        return;
      }

      //判断是套餐，还是多规格，还是单规格
      if (data.isGroup == 1) {
        this.toSetMealPage({
          currentTarget: {
            dataset: {
              goods: data
            }
          }
        });
        return;
      } else if (data.isGroup == 0 && (data.goodsAttrType.length > 0 || data.goodsSpec.length > 0)) {
        //选规格
        //默认选中第一个规格，单规格则清空
        if (data.isSku == 0) {
          data.goodsSpec = [];
        } else {
          data.goodsSpec.forEach((item, index) => {
            item.specItem.forEach((item2, index2) => {
              if (index2 == 0) {
                item2.checked = true;
              } else {
                item2.checked = false;
              }
            });
          });
        }

        //多保存一个价格用于只有属性时商品价格计算
        data.attPrice = data.shopPrice

        data.count = 1;
        //初始化属性
        data.goodsAttrType.forEach((item, index) => {
          //判断是否必选
          item.goodsAttr.forEach((item2, index2) => {
            item2.count = 0;
          });
        });
        this.setData({
          showAddShoppingCar: true,
          goodsSpec: data,
        })
        this.undateAddShoppingData();
      } else {
        //单规格直接添加
        this.onAddGoods({
          currentTarget: {
            dataset: {
              type: 2,
              goodsId: data.id,
            }
          }
        });
      }
    },
    //规格点击时
    clickSpecItem(e) {
      let cIndex = e.currentTarget.dataset.index;
      let cIndex2 = e.currentTarget.dataset.index2;
      let data = this.data.goodsSpec;
      data.goodsSpec.forEach((item, index) => {
        item.specItem.forEach((item2, index2) => {
          if (index == cIndex) {
            if (index2 == cIndex2) {
              item2.checked = true;
            } else {
              item2.checked = false;
            }
          }
        });
      });
      data.count = 1;
      this.setData({
        goodsSpec: data,
      })
      this.undateAddShoppingData();
    },
    //规格数量减少时
    onSpecSubGoods() {
      let data = this.data.goodsSpec;
      if (data.count <= 1) {
        return;
      } else {
        data.count -= 1;
      }
      this.setData({
        goodsSpec: data,
      })
      this.undateAddShoppingData();
    },
    //规格数量增加时
    onSpecAddGoods() {
      let data = this.data.goodsSpec;
      console.log(data);
      if (data.isSku == 1) {
        if (data.count >= data.skuStock) {
          wx.showToast({
            title: '无库存',
            icon: "none",
          })
          return;
        }
      } else {
        if (data.count >= data.stock) {
          wx.showToast({
            title: '无库存',
            icon: "none",
          })
          return;
        }
      }

      data.count += 1;

      this.setData({
        goodsSpec: data,
      })
      this.undateAddShoppingData();
    },
    //属性选择-----------------------------------------------------开始
    //点击加属性时
    addGoodsAtt(e) {
      let index1 = e.currentTarget.dataset.index1;
      let index2 = e.currentTarget.dataset.index2;
      //console.log(index1);
      //console.log(index2);
      console.log(this.data.goodsSpec.goodsAttrType[index1]);
      console.log(this.data.goodsSpec.goodsAttrType[index1].goodsAttr[index2]);
      if (this.data.goodsSpec.goodsAttrType[index1].goodsAttr[index2].isSellOut == 1) {
        wx.showToast({
          title: '已沽清',
          icon: 'none',
        })
        return;
      }

      //判断是否是可复选
      if (this.data.goodsSpec.goodsAttrType[index1].childrenSelectType == 1) {
        this.data.goodsSpec.goodsAttrType[index1].goodsAttr[index2].count += 1;
      } else {
        this.data.goodsSpec.goodsAttrType[index1].goodsAttr[index2].count = this.data.goodsSpec.goodsAttrType[index1].goodsAttr[index2].count == 1 ? 0 : 1;
      }
      //判断是否可多选
      if (this.data.goodsSpec.goodsAttrType[index1].multipleChoice == 0) {
        if (this.data.goodsSpec.goodsAttrType[index1].goodsAttr[index2].count > 0) {
          this.data.goodsSpec.goodsAttrType[index1].goodsAttr.forEach((item3, index3) => {
            if (index3 != index2) {
              item3.count = 0;
            }
          });
        }
      }

      this.setData({
        goodsSpec: this.data.goodsSpec,
      })
      this.undateAddShoppingData();
    },
    //点击减属性时
    subGoodsAtt(e) {
      let index1 = e.currentTarget.dataset.index1;
      let index2 = e.currentTarget.dataset.index2;
      //console.log(index1);
      //console.log(index2);
      console.log(this.data.goodsSpec.goodsAttrType[index1]);
      if (this.data.goodsSpec.goodsAttrType[index1].goodsAttr[index2].count <= 0) {
        return;
      }
      this.data.goodsSpec.goodsAttrType[index1].goodsAttr[index2].count -= 1;
      this.setData({
        goodsSpec: this.data.goodsSpec,
      })
      this.undateAddShoppingData();
    },
    //属性选择-----------------------------------------------------结束
    //多规格直接结算或者添加购物车，isNowBuy:是否直接结算
    moreSpecGoodsAddCart(e) {

      //是否直接结算
      let isNowBuy = e.currentTarget.dataset.isNowBuy;
      //判断是否有必填属性未填
      let haveMust = false;
      for (let i = 0; i < this.data.goodsSpec.goodsAttrType.length; i++) {
        if (this.data.goodsSpec.goodsAttrType[i].isMustChoice == 1) {
          haveMust = true;
          for (let j = 0; j < this.data.goodsSpec.goodsAttrType[i].goodsAttr.length; j++) {
            if (this.data.goodsSpec.goodsAttrType[i].goodsAttr[j].count > 0) {
              haveMust = false;
            }
          }
          if (haveMust) {
            wx.showToast({
              title: this.data.goodsSpec.goodsAttrType[i].typeName + '未选择',
              icon: 'none'
            })
            return;
          }
        }
      }
      //获取已经选中得属性
      let attrList = [];
      this.data.goodsSpec.goodsAttrType.forEach((item, index) => {
        item.goodsAttr.forEach((item2, index2) => {
          if (item2.count > 0) {
            attrList.push({
              count: item2.count,
              id: item2.attrId,
              price: item2.price,
            });
          }
        });
      });
      console.log('attrList', attrList)
      //把选择的多规格信息传入购物车
      let goodsMessage = this.data.goodsSpec;
      // let goodsSkuNameStr = goodsMessage.goodsSkuName.join('_')

      //加入购物车
      let shoppingCarGoodsList = this.data.shoppingCarGoodsList;
      //是否已经存在
      let isHaveGoods = false;
      let isStock = false;
      shoppingCarGoodsList.forEach((item, index) => {
        //商品相等，规格相等，属性相等
        if (item.id == goodsMessage.id && item.skuId == goodsMessage.skuId && item.goodsArrIds == goodsMessage.goodsArrIds) {
          item.count += goodsMessage.count;
          isHaveGoods = true;
        }
      });
      this.data.goodsSpec.goodsSku.forEach((item, index) => {
        if ((item.skuName == this.data.goodsSpec.goodsSkuNameStr) && item.stock == 0) {
          console.log("(item.skuName c", item.skuName, this.data.goodsSpec.goodsSkuNameStr);

          return isStock = true;
        }
      });
      if (isStock) {
        wx.showToast({
          title: this.data.goodsSpec.goodsSkuName + "该组合已售罄",
          icon: 'none'
        })
        return
      }

      //不存在时
      if (!isHaveGoods) {
        shoppingCarGoodsList.push({
          checked: true,
          id: goodsMessage.id,
          attrList: attrList,
          cateId: goodsMessage.cateId,
          count: goodsMessage.count,
          goodsId: goodsMessage.id,
          packageList: [],
          packageListString: JSON.stringify(),
          skuId: goodsMessage.skuId,
          thumbUrl: goodsMessage.thumbUrl,
          goodsName: goodsMessage.goodsName,
          goodsSkuName: goodsMessage.goodsSkuName,

          goodsArrName: goodsMessage.goodsArrName,
          goodsArrIds: goodsMessage.goodsArrIds,
          shopPrice: goodsMessage.shopPrice,
          originPrice: goodsMessage.originPrice,
        });
      }
      //购物车数
      let shoppingCarGoodsListTotal = 0;
      shoppingCarGoodsList.forEach((item, index) => {
        shoppingCarGoodsListTotal += item.count;
        //如果是立即结算把购物车其他商品全部设为非选中
        if (isNowBuy) {
          if (item.id == goodsMessage.id && item.skuId == goodsMessage.skuId && item.goodsArrIds == goodsMessage.goodsArrIds) {
            item.checked = true;
          } else {
            item.checked = false;
          }
        }
      });

      this.setData({
        shoppingCarGoodsList: shoppingCarGoodsList,
        shoppingCarGoodsListTotal: shoppingCarGoodsListTotal,
        showAddShoppingCar: false,
      });
      this.countPriceTotal();
      //立即结算直接跳确认订单页
      if (isNowBuy) {
        this.updateAllShoppingCarGoods();
        this.toOrderConfirm();
      }
    },
    //更新添加购物车的价格和规格文字，选择规格,选择的属性等
    undateAddShoppingData() {
      let data = this.data.goodsSpec;
      let selectIds = [];
      let goodsSkuName = [];
      let goodsSkuNameStr = '';
      if (data.isSku == 1) {
        data.goodsSpec.forEach((item, index) => {
          item.specItem.forEach((item2, index2) => {
            if (item2.checked) {
              selectIds.push(item2.id);
              goodsSkuName.push(item2.itemName);


            }
          });
        });
        data.goodsSkuNameStr = goodsSkuName.join("_")
        data.goodsSkuName = '[' + goodsSkuName.join(",") + "]";

        //小到大排序
        let specsId = sortToBig(selectIds).join("_");
        data.goodsSku.forEach((item, index) => {
          if (item.specsId == specsId) {
            data.shopPrice = item.shopPrice * 1;
            data.skuId = item.id;
            data.skuStock = item.stock;
          }

        });
      } else {
        data.shopPrice = data.attPrice
      }


      //计算属性价格
      let attPrice = 0;
      let goodsArrName = "";
      let goodsArrIds = "";

      data.goodsAttrType.forEach((item, index) => {
        item.goodsAttr.forEach((item2, index2) => {
          attPrice = attPrice + item2.price * item2.count;
          if (item2.count != 0) {
            if (item2.count == 1) {
              goodsArrName += item2.attrName + ","
            } else {
              goodsArrName += item2.attrName + "*" + item2.count + ","
            }
            goodsArrIds += item2.attrId + "*" + item2.count + ","
          }
        });
      });
      if (goodsArrName != '') {
        data.goodsArrName = goodsArrName.substring(0, goodsArrName.length - 1);
      } else {
        data.goodsArrName = goodsArrName
      }
      //是否显示vip价格
      let discount = 1;
      if (data.isShowVipPrice) {
        discount = this.data.vipInfo.discount;
      }
      data.goodsArrIds = goodsArrIds;
      data.originPrice = this.floatPrice((data.shopPrice * 1 + attPrice));
      data.shopPrice = this.floatPrice((data.shopPrice * 1 + attPrice) * discount);
      //商品价格+属性价格
      this.setData({
        goodsSpec: data,
      })
    },
    //关闭添加购物车
    hideAddShoppingCar(e) {

      this.setData({
        showAddShoppingCar: false
      })
    },

    //前往套餐页
    toSetMealPage(e) {
      //套餐信息存进全局

      let goods = e.currentTarget.dataset.goods;
      //是否显示vip价格
      let discount = 1;
      if (goods.isShowVipPrice) {
        discount = this.data.vipInfo.discount;
      }
      goods.originPrice = goods.shopPrice;
      goods.shopPrice = this.floatPrice(goods.shopPrice * discount);
      app.globalData.setMealInfo = goods;
      wx.navigateTo({
        url: '../../pages/setMeal/setMeal',
      })
    },

    //点击商品时
    onGoodsClick(e) {
      let goods = e.currentTarget.dataset.goods;
      //库存大于0
      if (goods.stock > 0) {
        if (goods.isGroup == 1) {
          //套餐
          this.toSetMealPage({
            currentTarget: {
              dataset: {
                goods: goods
              }
            }
          });
        } else if (goods.isGroup == 0 && (goods.goodsAttrType.length > 0 || goods.goodsSpec.length > 0)) {
          //有规格，或者属性
          this.showAddShoppingCar({
            currentTarget: {
              dataset: {
                id: goods.id
              }
            }
          })
        } else {
          //单规格
          this.onAddGoods({
            currentTarget: {
              dataset: {
                typeIndex: e.currentTarget.dataset.typeIndex,
                goodsIndex: e.currentTarget.dataset.goodsIndex,
                type: 1,
              }
            }
          })
        }
      }
    },

    //前往确认订单页
    toOrderConfirm() {
      let that = this;
      console.log('toOrderConfirm里面的orderType', this.data.orderType)
      //判断店铺是否已经打烊

      if (this.data.shopInfo.shopOpen == 1 && this.data.isPlaceOrder == 0) {
        wx.showToast({
          title: '店铺已打烊',
          icon: 'none'
        })
        return;
      }
      let orderTypeOrder = that.data.orderType;
      // if(that.data.orderType == 5){
      //   orderTypeOrder = 2
      // }
      //判断店铺销售方式
      if (that.data.shopInfo.salesType.indexOf(orderTypeOrder) == -1) {
        let showTitle = "";
        if (that.data.orderType == 1) {
          showTitle = "外卖";
        } else if (that.data.orderType == 2) {
          showTitle = "堂食";
        } else if (that.data.orderType == 4) {
          showTitle = "自取";
        }
        wx.showModal({
          title: '提示',
          content: '店铺暂不支持' + showTitle,
          showCancel: false,
          success(res) {
            if (res.confirm) {} else if (res.cancel) {}
          }
        })
        return;
      }

      if (wx.getStorageSync("paymentPriority") == 1 && wx.getStorageSync('deskId') && this.data.orderType == 2) {
        app.globalData.deskName = wx.getStorageSync('deskName');
        this.setData({
          // orderType: 5,
          deskId: wx.getStorageSync('deskId'),
          deskName: wx.getStorageSync('deskName')
        })

      }
      //购物车保存到全局
      this.setData({
        showShoppingCar: false,
      });
      app.globalData.cartList = this.data.shoppingCarGoodsList;
      let goods = [];
      this.data.shoppingCarGoodsList.forEach((item, index) => {
        if (item.checked) {
          goods.push(item);
        }
      });
      if (goods.length == 0) {
        wx.showToast({
          title: '未选择商品',
          icon: 'none'
        })
        return;
      }
      wx.navigateTo({
        url: '../orderConfirm/orderConfirm?saleType=' + this.data.saleType + "&orderType=" + this.data.orderType + "&deskCode=" + this.data.deskCode + "&deskId=" + this.data.deskId + "&orderId=" + this.data.orderId,
      })
    },

    toCouponPage() {
      wx.navigateTo({
        url: '/pages/coupon/getCoupon/getCoupon',
      })
    },

    //前往商品详情页
    goGoodsDetail(e) {
      console.log('this.data.orderType 传递的参数', this.data.orderType)
      let item = e.currentTarget.dataset.item;
      if (item.stock <= 0) {
        wx.showToast({
          title: '已售罄',
          icon: 'none'
        })
        return;
      }
      if (item.isGroup == 1) {
        //套餐
        this.toSetMealPage({
          currentTarget: {
            dataset: {
              goods: item
            }
          }
        });
      } else {

        wx.navigateTo({
          url: '/pages/goodsDetail/goodsDetail?id=' + item.id + '&saleType=' + this.data.saleType + "&orderType=" + this.data.orderType + "&deskCode=" + this.data.deskCode + "&deskId=" + this.data.deskId + "&orderId=" + wx.getStorageSync('orderId'),
        })
      }

    },

    //选择左边tab时
    tabSelect(e) {
      this.setData({
        TabCur: e.currentTarget.dataset.id,
        MainCur: e.currentTarget.dataset.id,
        //VerticalNavTop: e.currentTarget.dataset.id * 50
      })
    },
    //商品滚动时
    VerticalMain(e) {
      let that = this;
      let list = this.data.goodsInfo;

      if (this.data.load) {
        //列表上方的高度，状态栏+人气推荐
        let tabHeight = that.data.couponImgBoxHeight + that.data.hotGoodsBoxHeight;
        for (let i = 0; i < list.length; i++) {
          let view = wx.createSelectorQuery().select("#main-" + list[i].id);
          view.fields({
            size: true
          }, data => {

            list[i].top = tabHeight;
            tabHeight = tabHeight + data.height;
            list[i].bottom = tabHeight;
          }).exec();
        }
        that.setData({
          load: false,
          goodsInfo: list
        })
      }

      let scrollTop = e.detail.scrollTop;

      for (let i = 0; i < list.length; i++) {
        if (scrollTop > list[i].top && scrollTop < list[i].bottom) {
          if (that.data.TabCur != list[i].id) {
            that.setData({
              VerticalNavTop: (list[i].id) * 50,
              TabCur: list[i].id
            })
          }
          return false
        }
      }
    }
  }
}